package com.stalkernet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.location.Location;

public class UserPoller extends Thread {
    HashMap<String,Location> friends;
    int user;
    StalkernetManager sm;
	public UserPoller(HashMap<String,Location> friends, int userid, StalkernetManager sm)
	{
		this.friends=friends;
		this.user=userid;
		this.sm=sm;
	}
    // This method is called when the thread runs
    public void run()
    {
    	while(true)
    	{
    	try {
			String urlSearch = "http://astar.xvm.mit.edu/getLocations/"+user+"/";
			URL astarSearch = new URL(urlSearch);
			BufferedReader in = new BufferedReader(
					new InputStreamReader(astarSearch.openStream()));
			String result = "";
			String inputLine;
			
			while ((inputLine = in.readLine()) != null)
			    result += inputLine;
			in.close();
			result.replaceAll("\n", "");
			JSONObject jobj = new JSONObject(result);
			
			JSONArray buss = jobj.getJSONArray("locs");
			for (int i = 0; i < buss.length(); i++) {
				JSONObject bus = buss.getJSONObject(i);
				double lat=(new Double(bus.getString("lat")));
				double lng=(new Double(bus.getString("lng")));
				Location l=new Location("");
				l.setLatitude(lat);
				l.setLongitude(lng);
				friends.put(bus.getString("username"),l);
			}
			sm.updateMap();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}
		try
		{
			Thread.sleep(1000);
		} catch (InterruptedException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	}
    }
}
